﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZFY.Core;

namespace ZFY.AspNetCore
{
    public static class ConfigureExtension
    {
        public static IApplicationBuilder UseZFY(
            this IApplicationBuilder builder)
        {
            builder.Use(async (context, next) =>
            {
                if (context.User.Identity.IsAuthenticated)
                {
                    var profile = context.RequestServices.GetRequiredService<CurrentUserProfile>();
                    profile.PhoneNumber = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.PhoneNumber)?.Value;
                    profile.UserName = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.Name)?.Value;
                    profile.Avatar = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.Avatar)?.Value;
                    profile.Email = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.Email)?.Value;
                    profile.NickName = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.NickName)?.Value;
                    profile.UserId = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.UserId)?.Value;
                    profile.Address = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.Address)?.Value;
                    profile.Birthday = context.User.Claims.FirstOrDefault(x => x.Type == ZFYProfileClaimTypes.Birthday)?.Value;
                }

                await next();
            });

            return builder.UseMiddleware<ZFYExpectionMiddleware>();
        }
    }
}
